package com.github.hgkmail.hello.leetcode101.pointer.linkedlist;

import com.github.hgkmail.hello.leetcode101.base.CommonUtil;
import com.github.hgkmail.hello.leetcode101.base.ListNode;
import javafx.util.Pair;

public class LC24SwapNodesInPairs {
    //helper
    //交换curr和curr.next
    public void swapNode(ListNode curr, ListNode prev) {
        if (curr==null || curr.next==null) {
            return;
        }
        ListNode follow = curr.next;

        //prev->[curr->follow]->t
        ListNode t = follow.next;
        follow.next = curr;
        curr.next=t;
        prev.next=follow;

        swapNode(t, curr);
    }

    public ListNode swapPairs(ListNode head) {
        //dummyHead、dummyTail可以简化代码
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;

        ListNode curr = head;
        ListNode prev = dummyHead;
        swapNode(curr, prev);

        return dummyHead.next;
    }

    public static void main(String[] args) {
        ListNode a=new ListNode(4, null);
        ListNode b=new ListNode(3, a);
        ListNode c=new ListNode(2, b);
        ListNode d=new ListNode(1, c);
        CommonUtil.printLinkedList(d);
        CommonUtil.printLinkedList(new LC24SwapNodesInPairs().swapPairs(d));

    }
}
